import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // 跨域请求时发送cookies
  timeout: 50000 // 请求超时
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (res.code !== 0) {
      Message({
        message: res.message || res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token 非法令牌; 50012: Other clients logged in 其他客户端已登录; 50014: Token expired 令牌已过期;
      // eslint-disable-next-line eqeqeq
      if (res.code == -1 && res.msg == '未登陆') {
        // to re-login
        MessageBox.confirm('您已注销，您可以取消以停留在此页，或重新登陆', '确认注销', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      if (response.status !== 200) {
        return Promise.reject(new Error(res.message || 'Error'))
      }
    }
    return res
  },
  error => {
    console.log('err' + error) // for debug
    if (error.message.includes('timeout')) { // 判断请求异常信息中是否含有超时timeout字符串
      Message({
        message: '请求超时',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    } else if (error.message.includes('Network')) {
      Message({
        message: '网络错误',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    } else if (error.message.includes('404')) {
      Message({
        message: `请求失败，状态代码为404`,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    } else if (error.message.includes('400')) {
      Message({
        message: `请求失败，状态代码为400`,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    } else if (error.message.includes('500')) {
      Message({
        message: `请求失败，状态代码为500`,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
